﻿//with thanks to code sample from http://weblogs.asp.net/rashid/archive/2008/03/28/asp-net-mvc-action-filter-caching-and-compression.aspx 
using System;
using System.Web;
using System.Web.Mvc;
using System.IO.Compression;

namespace DataConDemoWebRole
{
    /// <summary>
    /// This attribute can be applied to a class or method to force a compressed return,
    /// which will ordinarily not happen with POST operations, or even GETs of non-cached data.
    /// </summary>
    public class CompressFilter : ActionFilterAttribute
    {
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var request = filterContext.HttpContext.Request;
            var acceptEncoding = (request.Headers["Accept-Encoding"] ?? "").ToLowerInvariant();
            var response = filterContext.HttpContext.Response;

            if (acceptEncoding.Contains("gzip"))
            {
                response.AppendHeader("Content-Encoding", "gzip");
                response.Filter = new GZipStream(response.Filter, CompressionMode.Compress);
            }
            else if (acceptEncoding.Contains("deflate"))
            {
                response.AppendHeader("Content-Encoding", "deflate");
                response.Filter = new DeflateStream(response.Filter, CompressionMode.Compress);
            }
        }
    }
}